package cn.jiedh.app.meiweidk.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jiedh.app.meiweidk.MyWebActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.UI.VerticalSpaceItemDecoration;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.DensityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.DeviceUtils;
import cn.jiedh.app.meiweidk.Utils.tool.NumUtils;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.buried.BuriedBean;
import cn.jiedh.app.meiweidk.entity.productLinkTransferBean;
import cn.jiedh.app.meiweidk.homepage.NewProductData;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.newpeopleproduct.NewPeopleProductListActivity;
import cn.jiedh.app.meiweidk.newpeopleproduct.NewProduct;
import cn.jiedh.app.meiweidk.response.BaseResponse;

/**
 * @name：我的额度
 * @author：无崖子
 * @phone：15330488824
 * @createTime：2018/11/22
 */

public class MyQuotaActivity extends BaseActivity {
    @BindView(R.id.statelayout)
    StateLayout statelayout;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;
    @BindView(R.id.quota_list)
    EmptyRecyclerView quota_list;
    private View emptyView;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;

    @BindView(R.id.amount_num)
    TextView amount_num;

    private List<NewProduct> quotaList = new ArrayList<>();
    BaseAdapter<NewProduct> adapter;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_my_quota;
    }

    @Override
    protected void initView(View view) {
        setTitle("我的额度");
        StatusBarUtil.setTransparentForImageView(this, null);

//        smartrefreshLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(final RefreshLayout refreshlayout) {
//                refreshlayout.getLayout().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        statelayout.netviewGone();
//                        sendRequest();
//                        refreshlayout.finishRefresh();
//                    }
//                }, 2000);
//            }
//        });
//        smartrefreshLayout.autoRefresh();

    }

    @Override
    protected void initData() {
        emptyView = findViewById(R.id.emptyview);
        emptyNnPic.setImageResource(R.mipmap.mylljl);
        emptyNnBtn.setText("暂无数据");
        adapter = new BaseAdapter<NewProduct>(activity, R.layout.layout_home_groom, quotaList) {
            @Override
            public void convert(BaseViewHolder holder, NewProduct newProduct, int position) {
                holder.setImageUrl(R.id.home_groom_iv, newProduct.getImgUrl());
                holder.setText(R.id.home_groom_name, newProduct.getName());
                holder.setText(R.id.loan_advert, newProduct.getAdver());
                String moneyMin = newProduct.getMoneyMin() + "";
                String moneyMax = newProduct.getMoneyMax() + "";
                if (moneyMin.length() >= 6) {
                    moneyMin = newProduct.getMoneyMin() / 10000 + "";
                } else {
                    moneyMin = newProduct.getMoneyMin() + "";
                }
                if (moneyMax.length() >= 6) {
                    moneyMax = newProduct.getMoneyMax() / 10000 + "万";
                } else {
                    moneyMax = newProduct.getMoneyMax() + "";
                }
                holder.setText(R.id.home_groom_ad, moneyMin + "-" + moneyMax);

                holder.setText(R.id.loan_daily_rate, NumUtils.getTwoDecimal(newProduct.getRate()) + "%");
                holder.setText(R.id.rate_type_tv, "参考" + newProduct.getRateTypeStr() + "利率");

                holder.setText(R.id.loan_success_rate, newProduct.getJianjun() + "");
                holder.getView(R.id.new_product_).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        MobclickAgent.onEvent(MyQuotaActivity.this, "Quota_item");

                        List<BuriedBean> buriedList = new ArrayList<BuriedBean>();
                        buriedList.add(new BuriedBean("click", "", "0", newProduct.getProductId() + "", newProduct.getName(), "", "false", "", "", "",
                                "", "", "", "", "", newProduct.getRate() + "", ""));
                        SPUtils.saveBuriedList(buriedList);

                        Bundle bundle = new Bundle();
                        bundle.putInt("productId", newProduct.getProductId());
                        ActivityUtil.next(activity, LoanDetailActivity.class, bundle);
                    }
                });


                TextView goApply_tv=holder.getView(R.id.goApply_tv);
                goApply_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        apply(newProduct.getProductId(),newProduct.getApplyUrl(),newProduct.getName());
                    }
                });
            }
        };
        quota_list.setLayoutManager(new LinearLayoutManager(this));
        quota_list.addItemDecoration(new VerticalSpaceItemDecoration(DensityUtil.dip2px(MyQuotaActivity.this, 10), false));
        quota_list.setAdapter(adapter);
        sendRequest();
    }



    /**
     * 统计并跳转
     *
     * @param productId
     * @param applyUrl
     * @param loanTitle
     */
    private void apply(int productId, String applyUrl, String loanTitle) {
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.ADDBROWSE, map, false, new ResponseSuccess<String>() {
            @Override
            public void onRequestSucceed(BaseResponse response) {
                dismissLoadingDialog();
                if (0 == response.getCode()) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("url", applyUrl);
//                    bundle.putString("title", loanTitle);
//                    Intent intent = new Intent(getActivity(), MyWebActivity.class);
//                    intent.putExtras(bundle);
//                    startActivityForResult(intent, 1);
                    productLinkTransfer(productId,applyUrl,loanTitle);
                } else {
                    T.showShort(response.getMessage());
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }

    /**
     * 是否是联合登陆的产品
     */
    private void productLinkTransfer(int productId,String applyUrl,String loanTitle){
        showLoadingDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("productId", productId + "");
        request(UrlUtils.PRODUCT_LINK_TRANSFER, map, false, new ResponseSuccess<productLinkTransferBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<productLinkTransferBean> response) {
                dismissLoadingDialog();
                Intent intent = new Intent(MyQuotaActivity.this, MyWebActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("title", loanTitle);
                if (0 == response.getCode()) {
                    bundle.putString("url", response.getData().getApplyUrl());
                } else {
                    bundle.putString("url", applyUrl);
                }
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                T.show(msg);
                dismissLoadingDialog();
            }
        });
    }




    private void sendRequest() {
        Map<String, Object> map = new HashMap<>();
//        map.put("pageNo", 1);
//        map.put("pageSize", "2");
//        map.put("money", "8000");
        request(activity, UrlUtils.AMOUNMATE, map, true, new ResponseSuccess<NewProductData>() {

            @Override
            public void onRequestSucceed(BaseResponse<NewProductData> response) {
                if (response.getCode() == 0) {
                    if (response.getData() != null && response.getData().getDataList() != null) {
                        amount_num.setText("¥"+response.getData().getAmount());

                        quota_list.setEmptyView(emptyView);
                        quotaList.addAll(response.getData().getDataList());
                        adapter.notifyDataSetChanged();
                    }
                } else {
                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
            }
        });
    }
}
